package com.eorchis.module.interioruser.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.eorchis.core.basedao.dao.impl.HibernateAbstractBaseDao;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.basedao.query.condition.IPagingQueryCondition;
import com.eorchis.core.basedao.query.condition.builder.CompareType;
import com.eorchis.core.basedao.query.condition.builder.IConditionBuilder;
import com.eorchis.core.basedao.query.condition.builder.impl.DefaultQueryConditionBuilder;
import com.eorchis.core.page.commond.SortInfoBean;
import com.eorchis.core.ui.commond.IQueryCommond;
import com.eorchis.module.classuser.domain.ClassUser;
import com.eorchis.module.classuser.domain.QueryClassUserBean;
import com.eorchis.module.interioruser.dao.IInteriorUserDao;
import com.eorchis.module.interioruser.domain.DeptSignupBean;
import com.eorchis.module.interioruser.domain.InteriorUser;
import com.eorchis.module.interioruser.domain.InteriorUserQueryBean;
import com.eorchis.module.interioruser.domain.UserInfoBean;
import com.eorchis.module.interioruser.ui.commond.InteriorUserQueryCommond;
import com.eorchis.module.interioruser.ui.commond.InteriorUserValidCommond;
import com.eorchis.module.user.domain.User;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: InteriorUserDaoImpl<br>
 * Description: 内部用户数据接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Administrator
 * @createDate 2015-01-04
 * @version $Revision$
 */
@SuppressWarnings("unchecked")
@Repository(value = "com.eorchis.module.interioruser.dao.impl.InteriorUserDaoImpl")
public class InteriorUserDaoImpl extends HibernateAbstractBaseDao implements IInteriorUserDao {
	
	@Override
	public Class<? extends IBaseEntity> entityClass() {
		return InteriorUser.class;
	}

	@Override
	public void queryConditionProcessor(
			IConditionBuilder defaultQueryConditionBuilder,
			IQueryCommond queryCommond) {
		InteriorUserQueryCommond interiorUserQueryCommond = (InteriorUserQueryCommond)queryCommond;
		defaultQueryConditionBuilder.setBaseQueryString("SELECT t FROM InteriorUser t");
		defaultQueryConditionBuilder.addCondition("t.userid", CompareType.IN, interiorUserQueryCommond.getSearchUserids());
	}


	public InteriorUserQueryBean preUpdateInteriorUser(InteriorUserQueryCommond qCommond) throws Exception{
		StringBuffer hql = new StringBuffer();
		hql.append(" select iu.userid as userId,iu.user.loginID as loginId,iu.userName as userName ,t.deptName as deptName from ");
		hql.append(" InteriorUser iu , DepartmentUser tu    ");
		hql.append(" , Department t   where iu.user.loginID =:loginId and iu.userid = tu.user.userId and t.deptID = tu.department.deptID ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginId", qCommond.getSearchLoginid());
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.HQL);
		defaultQueryConditionBuilder.setResultObject(InteriorUserQueryBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<InteriorUserQueryBean> list= (List<InteriorUserQueryBean>) this.findList(queryCondition);
		return list.get(0);
	}

	@Override
	public int updateInteriorUser(
			InteriorUserValidCommond vCommond) throws Exception {
		StringBuffer hql = new StringBuffer();
		hql.append(" update interior_user  i SET i.user_name =:userName where i.userid = :userid");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("userName" ,vCommond.getUserName());
		params.put("userid",vCommond.getUserid());
		int count=this.executeUpdate(QueryStringType.SQL, hql.toString(), params);
		return count;
	}
	@Override
	public int updateBaseUser(
			InteriorUserValidCommond vCommond) throws Exception {
		StringBuffer hql = new StringBuffer();
		hql.append(" update base_user  t SET t.user_name =:userName where t.userid = :userid");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("userName" ,vCommond.getUserName());
		params.put("userid",vCommond.getUserid());
		int count=this.executeUpdate(QueryStringType.SQL, hql.toString(), params);
		return count;
	}
	
	/**
	 * 验证用户是否存在
	 * @param validCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月7日
	 */
	@Override
	public UserInfoBean checkUserIsIn(InteriorUserValidCommond validCommond) throws Exception{		
//		String sql="select t.login_id as \"loginID\" ,t.userid as \"userId\" from base_user t where t.login_id= :loginId";
		StringBuffer sql=new StringBuffer();
		sql.append(" select t.login_id as \"loginID\", t.userid as \"userId\" ,d.depid as \"depID\" ,d.treepath as \"treepath\",t.user_name as \"userName\" ");
		sql.append(" from base_user t, BASE_DEPARTMENT_USER du, BASE_DEPARTMENT d ");
		sql.append(" where 1=1 ");
		sql.append(" and t.userid=du.userid ");
		sql.append(" and du.depid=d.depid ");
		sql.append(" and t.login_id = :loginId ");	
		sql.append(" and t.active_state = :activeState ");
//		String sql="select t.login_id as \"loginID\" ,t.userid as \"userId\" from base_user t where t.login_id= :loginId";
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("loginId",validCommond.getLoginId());
		params.put("activeState",1);
//		User.IS_ACTIVE_Y;
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(sql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setResultObject(UserInfoBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<UserInfoBean> findList = (List<UserInfoBean>) this.findList(queryCondition);
		if(PropertyUtil.objectNotEmpty(findList)){
			UserInfoBean user=findList.get(0);
			return user;
		}
		return null;		
	}

	/**
	 * 验证用户是否在班级内
	 * @param validCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月7日
	 */
	public ClassUser checkUserInClass(InteriorUserQueryCommond queryCommond) throws Exception{		
		StringBuffer hql=new StringBuffer();
		hql.append(" from ClassUser t  where 1=1" );
		Map<String,Object> params=new HashMap<String, Object>();
		//用户id
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchUserId())){
			hql.append(" and t.user.userId= :userId" );
			params.put("userId", queryCommond.getSearchUserId());
		}
		//报名年限 
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchSigupYear())){
			hql.append(" and t.signUpYear= :signUpYear" );
			params.put("signUpYear", queryCommond.getSearchSigupYear());
		}	
		//班级id
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchClassId())){
			hql.append(" and t.trainingClass.classId= :classId" );
			params.put("classId", queryCommond.getSearchClassId());
		}
		//用户名
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchLoginIds())){
			hql.append(" and t.user.loginID in (:loginIds)" );
			params.put("loginIds", queryCommond.getSearchLoginIds());
		}
		//用户ids
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchUserIds())){
			hql.append(" and t.user.userId in (:userIds)" );
			params.put("userIds", queryCommond.getSearchUserIds());
		}
		hql.append(" and t.auditingState= :auditingState" );
		params.put("auditingState", ClassUser.IS_AUDITING_Y);
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.HQL);
//		defaultQueryConditionBuilder.setResultObject(ClassUser.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<ClassUser> findList = (List<ClassUser>) this.findList(queryCondition);
		if(PropertyUtil.objectNotEmpty(findList)){
			ClassUser classUser=findList.get(0);
			return classUser;
		}
		return null;		
	}
	
	/**
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月8日
	 */
//	public List<DeptSignupBean> getDeptSignupInfo(InteriorUserQueryCommond queryCommond) throws Exception{		
//		StringBuffer hql=new StringBuffer();
//		hql.append(" select bd.depid as \"depID\",  bd.depname \"depName\", (select count(cu.class_user_id)  from TRAINING_CLASS_USER  cu, BASE_DEPARTMENT_USER du, BASE_DEPARTMENT d,BASE_USER u " );		
//		hql.append(" where cu.user_id = u.userid  and du.depid = d.depid and du.userid = u.userid and d.treepath like :treepath and cu.signup_year = :signUpYear and cu.AUDITING_STATE=:auditingState ) as \"signupNum\" " );	
//		hql.append(" from BASE_DEPARTMENT  bd  where  bd.treepath like :treepath " );
//		Map<String,Object> params=new HashMap<String, Object>();
//		params.put("signUpYear", queryCommond.getSearchSigupYear());
//		params.put("treepath", queryCommond.getSearchTreepath()+"%");
//		params.put("auditingState", ClassUser.IS_AUDITING_Y);
//		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
//		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
//		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
//		defaultQueryConditionBuilder.setResultObject(DeptSignupBean.class);
//		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
//		queryCondition.setParameters(params);
//		List<DeptSignupBean> findList = (List<DeptSignupBean>) this.findList(queryCondition);
//		return findList;		
//	}
	
	public List<DeptSignupBean> getDeptSignupNum(InteriorUserQueryCommond queryCommond) throws Exception{		
		StringBuffer hql=new StringBuffer();
		Map<String,Object> params=new HashMap<String, Object>();
		hql.append(" select count(cu.class_user_id) as \"signupNum\"  from TRAINING_CLASS_USER  cu, BASE_DEPARTMENT_USER du, BASE_DEPARTMENT d,BASE_USER u,TRAINING_CLASS c " );		
		hql.append(" where cu.user_id = u.userid  and du.depid = d.depid and du.userid = u.userid and c.class_id=cu.class_id and d.treepath like :treepath and cu.signup_year = :signUpYear and cu.AUDITING_STATE=:auditingState " );
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchClassId())){
			hql.append(" and cu.class_id= :classId");
			params.put("classId", queryCommond.getSearchClassId());
		}
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchClassTypeList())){
			hql.append(" and c.class_type in(:classType)");
			params.put("classType", queryCommond.getSearchClassTypeList());
		}
		params.put("signUpYear", queryCommond.getSearchSigupYear());
		params.put("treepath", queryCommond.getSearchTreepath()+"%");
		params.put("auditingState", ClassUser.IS_AUDITING_Y);
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setResultObject(DeptSignupBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<DeptSignupBean> findList = (List<DeptSignupBean>) this.findList(queryCondition);
		return findList;		
	}
	/**
	 * 由登录号查询用户
	 * @param validCommond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015年1月15日
	 */
	@Override
	public User getUserByLoginId(String loginId) throws Exception{		
		String sql="select t.login_id as \"loginID\" ,t.userid as \"userId\" ,t.user_Name as \"userName\" from base_user t where t.login_id= :loginId";
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("loginId",loginId);
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(sql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setResultObject(User.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<User> findList = (List<User>) this.findList(queryCondition);
		if(PropertyUtil.objectNotEmpty(findList)){
			User user=findList.get(0);
			return user;
		}
		return null;		
	}
	/**
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月23日
	 */
	public long getClassSingUpNum(InteriorUserQueryCommond queryCommond) throws Exception{		
		String hql="from ClassUser cu where cu.trainingClass.classId=:classId and cu.auditingState=1";		
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("classId", queryCommond.getSearchClassId());
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.HQL);
		defaultQueryConditionBuilder.setResultObject(User.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		Long count=this.count(queryCondition);
		return count;		
	}
	/**
	 * 验证用户是否在报名单位里
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月25日
	 */
	public boolean checkUserInSignUpDept(InteriorUserQueryCommond queryCommond) throws Exception{
		String hql=" select * from SIGNUP_DEPT t where :treepath like t.treepath || '%'   and t.id not in ('-1', '1') ";		
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("treepath", queryCommond.getSearchTreepath());
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setResultObject(User.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		Long count=this.count(queryCondition);	
		if(count>1){
			return true;
		}
		return false;
	}
	/**
	 * 临时人员列表-单位and工委
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-5-6
	 */
	@Override
	public List<QueryClassUserBean> getLUserList(
			InteriorUserQueryCommond queryCommond) throws Exception {
		Map<String, Object> values = new HashMap<String, Object>();
		StringBuffer sql=new StringBuffer();
		sql.append(" select u.userid as \"userId\",u.login_id as \"loginID\",u.user_name as \"userName\" ,d.depname as \"depName\" ");
		sql.append(" from base_department_user du, base_department d, base_user u ");
		sql.append(" where u.userid = du.userid and du.depid = d.depid and du.active_state="+ClassUser.IS_ACTIVE_STATE_Y+" and d.active_state="+ClassUser.IS_ACTIVE_STATE_Y+" ");
		//如果是工委查询 不是按照登录号第四位是L查询 by Max at 2015-05-07
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchDepIds())) {
			sql.append(" and u.active_state="+ClassUser.IS_ACTIVE_STATE_Y+" and u.login_id like 'L%' ");
		}else {
			sql.append(" and u.active_state="+ClassUser.IS_ACTIVE_STATE_Y+" and u.login_id like '___L%' ");
		}
		//单位管理员按照Treepath查询临时用户
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchTreepath())){
			sql.append(" and d.treepath like :treepath ");
			values.put("treepath", queryCommond.getSearchTreepath()+"%");
		}
		//工委管理员按照2个Treepath查询临时用户
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchDepIds())){
			sql.append(" and (d.treepath like :treepath1 or d.treepath like :treepath2)");
			values.put("treepath1", queryCommond.getSearchTreePath1()+"%");
			values.put("treepath2", queryCommond.getSearchTreePath2()+"%");
		}
		//登陆号
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchLoginid())){
			sql.append(" and u.login_id like :loginID ");
			values.put("loginID", "%"+queryCommond.getSearchLoginid().trim()+"%");
		}
		//用户姓名
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchUserName())){
			sql.append(" and u.user_name like :userName ");
			values.put("userName", "%"+queryCommond.getSearchUserName().trim()+"%");
		}
		//拼写排序的sql
		List<SortInfoBean> sortInfoList = queryCommond.getSortInfo();
		if (sortInfoList != null && sortInfoList.size() > 0) {
			SortInfoBean sortInfo = sortInfoList.get(0);
			sql.append(" order by " + PropertyUtil.sqlInjectionFilter(sortInfo.getProperty()) + " " + PropertyUtil.sqlInjectionFilter(sortInfo.getDirection()));
		}
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setBaseQueryString(sql.toString());
		defaultQueryConditionBuilder.setResultObject(QueryClassUserBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(values);
		//查询总数量
		Long count = this.count(queryCondition);
		int firstResult = queryCommond.calculate(count.longValue());		
		List<QueryClassUserBean> resultList=(List<QueryClassUserBean>)this.findList(queryCondition,firstResult,queryCommond.getLimit());
		return resultList;
	}
	public InteriorUserQueryBean preUpdateUser(InteriorUserQueryCommond qCommond) throws Exception{
		StringBuffer hql = new StringBuffer();
		hql.append(" select iu.userId as userId,iu.loginID as loginId,iu.userName as userName ,t.deptName as deptName from ");
		hql.append(" User iu , DepartmentUser tu    ");
		hql.append(" , Department t   where iu.loginID =:loginId and iu.userId = tu.user.userId and t.deptID = tu.department.deptID ");
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("loginId", qCommond.getSearchLoginid());
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(hql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.HQL);
		defaultQueryConditionBuilder.setResultObject(InteriorUserQueryBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		List<InteriorUserQueryBean> list= (List<InteriorUserQueryBean>) this.findList(queryCondition);
		return list.get(0);
	}
}
